﻿
Imports std
Imports lock_t = lock(Of locks.monitorlock)

Public Module jobqueues
    Private Const count As UInt32 = 128
    Private d() As vector(Of pointer(Of pair(Of String, jobqueue))) = Nothing
    Private l() As lock_t

    Sub New()
        ReDim d(count - 1)
        ReDim l(count - 1)
        For i As Int32 = 0 To count - 1
            d(i) = New vector(Of pointer(Of pair(Of String, jobqueue)))()
        Next
    End Sub

    Private Function find(ByVal name As String, ByVal index As UInt32, ByRef q As jobqueue) As Boolean
        For i As Int32 = 0 To d(index).size() - 1
            If strsame(name, (+(d(index)(i))).first) Then
                q = (+(d(index)(i))).second
                Return True
            End If
        Next

        Return False
    End Function

    Public Function at(ByVal name As String) As jobqueue
        Dim index As UInt32 = 0
        index = signing(name) Mod count
        Dim q As jobqueue = Nothing
        If Not find(name, index, q) Then
            l(index).wait()
            If Not find(name, index, q) Then
                Dim p As pair(Of String, jobqueue) = Nothing
                q = New jobqueue(name)
                p = make_pair(name, q)
                assert(d(index).push_back(New pointer(Of pair(Of String, jobqueue))(p)))
            End If
            l(index).release()
        End If
        assert(Not q Is Nothing)
        Return q
    End Function
End Module
